﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using YArchitech.Controls;

namespace YArchitech.Revit
{
	public partial class UpdateProcessBar : System.Windows.Forms.Form
	{
		public UpdateProcessBar(Document doc, List<HYUpdateElementInfo> listNodes)
		{
			this.InitializeComponent();
			this.nodesToUpdate = listNodes;
			this.document = doc;
			this.progressBarCtrl.Maximum = listNodes.Count;
			this.backgroundWorkerUpdate.WorkerReportsProgress = true;
		}

		private void UpdateProcessBar_Shown(object sender, EventArgs e)
		{
			this.tran = new Transaction(this.document, "更新数据");
			this.tran.Start();
			this.backgroundWorkerUpdate.RunWorkerAsync();
		}

		private void backgroundWorkerUpdate_DoWork(object sender, DoWorkEventArgs e)
		{
		}

		private void backgroundWorkerUpdate_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			this.progressBarCtrl.Value = e.ProgressPercentage;
			int value = e.ProgressPercentage * 100 / this.nodesToUpdate.Count;
			this.tipText.Text = "正在更新图元:" + Convert.ToString(value) + "%";
		}

		private void backgroundWorkerUpdate_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			try
			{
				if (this.isUpdateSucceed)
				{
					this.document.Regenerate();
                    this.isUpdateSucceed = (this.tran.Commit() == (TransactionStatus)3);
				}
			}
			catch (Exception ex)
			{
				ex.ToString();
				this.isUpdateSucceed = false;
			}
			finally
			{
				if (this.tran != null && this.tran.GetStatus() != (TransactionStatus)3)
				{
					this.tran.RollBack();
					this.isUpdateSucceed = false;
				}
			}
			this.tran = null;
			bool flag = this.isUpdateSucceed;
			if (this.isUpdateSucceed)
			{
				YJKMessageBox.Information("更新数据成功！");
			}
			else
			{
				YJKMessageBox.Error(string.Format("更新数据失败: {0}!", this.updateOperation.FailedString));
			}
			base.Close();
		}

		protected List<HYUpdateElementInfo> nodesToUpdate;

		protected Document document;

		protected bool isUpdateSucceed;

		protected ElementsUpdater updateOperation;

		protected Transaction tran;
	}
}
